import React, { useState,useRef } from 'react';
import { Button, Badge, message,Drawer,Spin } from 'antd';
import {DrawerForm} from '@ant-design/pro-form';
import type { ProColumns,ActionType } from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import { PageContainer } from '@ant-design/pro-layout';
import DealerInfo from '../../../components/Common/DealerInfo'
import InputDialog from '../../../components/Common/InputDialog';
import {dealerDataById,aduitStatus,dealerListData} from '../../MasterData/service';
import UpDownLabel from '@/components/Common/UpDownLabel';
import {Dealer} from '../../../model';

const renderBadge = (count: number, active = false) => {
  return (
    <Badge
      count={count}
      style={{
        marginTop: -2,
        marginLeft: 4,
        color: active ? '#1890FF' : '#999',
        backgroundColor: active ? '#E6F7FF' : '#eee',
      }}
    />
  );
};

export default () => {
  const [activekey, setActiveKey] = useState<React.Key>('tab1');
  const [showApprove, setShowApprove] = useState(false);
  const [showDetail, setShowDetail] = useState(false);
  const [inputDialog, setInputDialog] = useState(false);
  const [dealInfo, setDealInfo] = useState<any>();
  const [spinningFlag,setSpinningFlag] = useState(false);
  const [note, setNote] = useState<string>("");

  const actionRef = useRef<ActionType>();

  const toApprove= async(record)=>{
    setSpinningFlag(true);
    var val = await dealerDataById({"dealerId":record.id});
    if(val.errorCode==='200'){
      if(val.data.ticket){
        val.data.ticket.areas=[val.data.ticket.provinces,val.data.ticket.city,val.data.ticket.area]
      }
      setDealInfo(val.data);
      if(activekey==='tab1'){
        setShowApprove(true);
      }else{
        setShowDetail(true);
      }
      setNote(record.note);
    }else{
      message.error('获取详细信息失败');
    }
    setSpinningFlag(false);

  }
  
  const columns: ProColumns<Dealer>[] = [
    {
      title: '客户代码',
      dataIndex: 'loginName',
    },
    {
      title: '客户名称',
      dataIndex: 'cnName',
    },
    {
      title: '地区',
      dataIndex: 'provinces_label',
      hideInSearch:true,
      render: (_, record:Dealer) => `${record.provinces_label}/${record.city_label}`
    },
    {
      title: '状态',
      dataIndex: 'status',
      hideInSearch:true,
      renderText:(v)=>{
        if(activekey=='tab2'){
          if(v==2){
            return '审核未通过'
          }
          return '审核通过'
        }
        if(v===2){
          return '审核未通过'
        }
        if(v===1){
          return '审核通过'
        }
        if(v===0){
          return '待激活'
        }
        if(v===3){
          return '待审核'
        }
      }
    },
    {
      title: '提交日期',
      dataIndex: 'submitTime',
      hideInSearch:true,
    },
    {
      title: '审核日期',
      dataIndex: 'checkTime',
      hideInTable:activekey=='tab1',
      hideInSearch:true,
    },
    {
      title: '审批人',
      hideInSearch:true,
      dataIndex: 'checker',
      width:80
    },
    {
      title: '操作',
      key: 'option',
      width: 120,
      valueType: 'option',
      render: (_, record) => [
        <a key="show" onClick={()=>toApprove(record)}>查看</a>,
      ],
    },
  ];

  return (
    <PageContainer>
    <ProTable<DealerInfo>
      columns={columns}
      actionRef={actionRef}
      request={async(params, sorter, filter) => {
        var other:any ={}
        if(activekey==='tab1'){
          other.status='3'
        }else{
          other.isChecked=true
        }
        return dealerListData( {...params,filter,...other});
      }}
      toolbar={{
        menu: {
          type: 'tab',
          activeKey: activekey,
          items: [
            {
              key: 'tab1',
              label: <span>待处理{renderBadge(0, activekey === 'tab1')}</span>,
            },
            {
              key: 'tab2',
              label: <span>已处理{renderBadge(0, activekey === 'tab2')}</span>,
            },
          ],
          onChange: (key) => {
            setActiveKey(key as string);
            actionRef.current?.reloadAndRest?.();
          },
        },
        actions:undefined,
        settings:[]
      }}
      rowKey={(record:any) => record.id+record.status + record.checkTime}
      dateFormatter="string"
      pagination={{
        pageSizeOptions:['20', '100', '500']
      }}
    />
      <Drawer
            width={1000}
            title="详情"
            visible={showDetail}
            onClose={()=>setShowDetail(false)}
            destroyOnClose={true}>
           <DealerInfo data={dealInfo} showForm={false}/>
          <div style={{marginTop:'20px'}} hidden={note===''}>
            <UpDownLabel title="未通过原因" texts={[note]}/>
          </div>
      </Drawer>
      <DrawerForm
          title={"详情"}
           onVisibleChange={setShowApprove}
           visible={showApprove}
           onFinish={async (values: any) => {
              values.dealerId=dealInfo.dealer.id;
              values.status='1';
              var val =await aduitStatus(values);
              if(val.errorCode==='200'){
                message.success('提交成功');
                actionRef.current?.reloadAndRest?.();
                return true;
              }else{
                message.error(val.errorMessage);
                return false;
              }
           }}
           drawerProps={{
            forceRender: true,
            destroyOnClose: true,
          }}
           submitter={{
            searchConfig:{
                submitText:"审核通过",
                resetText:"取消"
             },

            render: (props, defaultDoms) => {
              return [
                ...defaultDoms,
                <Button danger
                  key="back"
                  onClick={() => {
                    setInputDialog(true);
                  }}
                >
                  审核不通过
                </Button>,
              ];
            },
          }}
         >
           <DealerInfo data={dealInfo} showForm={false}/>
         </DrawerForm>
         <InputDialog
            inputFlag={true}
            onCancel={() => {
              setInputDialog(false);
            }}
            onSubmit={async (value) => {
              var data = value[0];
              var values:any={};
              values.note=data;
              values.dealerId=dealInfo.dealer.id;
              values.status='2';
              var val =await aduitStatus(values);
              if(val.errorCode==='200'){
                message.success('提交成功');
                setShowApprove(false);
                setInputDialog(false);
                actionRef.current?.reloadAndRest?.();
              }else{
                message.error(val.errorMessage);
              }
            }}
            modalVisible={inputDialog}
            title="审核不通过"
            label="审核不通过原因"
            placeholder="请填写审核不通过原因"
           >
        </InputDialog>
        <Spin spinning={spinningFlag} style={{transform:'translate(-50%:-50%)',left:'50%',top:'50%',position:'absolute'}}/>
    </PageContainer>
  );
};
